import React, { PropTypes, Component } from 'react';
import Column from './Column';
import Pagination from './Pagination';
import { findAllByType, isFunction } from './utils';
import orderIcon from './../imgs/orderIcon4.png'

export default React.createClass({
  PropTypes: {
    className: PropTypes.string,
    data: PropTypes.arrayOf(PropTypes.object),
    children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node]),
    needSum: PropTypes.oneOf(['false', 'true']),
  },
  getDefaultProps: function() {
    return {
      needSum: 'true',
    };
  },
  getInitialState: function () {
    return {
      data: [{}],
      rowData: this.props.data,//用于未分页的数据处理
      order: '',
      //totalNumber: this.props.data.length,
      //pageSize: 6,//默认每页5个数据
      //currentPage: 1,
      //middlePage: 5,//每页最少5个数据
    };
  },

  //初始化分页数据,只执行一次，如果外面是异步获取数据会有问题
  componentWillMount: function() {
    let rowData = this.props.data;
    //let data = this.Divide(rowData, this.state.pageSize);
    //this.setState({data: data[this.state.currentPage - 1]});
    this.setState({data: this.props.data});
  },

  /*Divide: function(array, size) {
    let result = [];
    for(let x=0; x<Math.ceil(array.length/size); x++) {
      let start = x * size;
      let end = start + size;
    result.push(array.slice(start, end));//注意slice会改变原数组
    }
    return result;
    console.log(result);
  },*/
  getDisplayName: function (el) {
    el && el.type && (el.type.displayName || el.type.name)
  },
  hasNames: function (columns) {
    let result = false;
    for (let i = 0, len = columns.length; i < len; i++) {
        const col = columns[i];
        const { name } = col.props;
        if (name && name !== '') {
          result = true;
        }
    }
    return result;
  },
  getStyle: function ({ width, align }) {
    const style = {};
    if (width) {
        style.width = width;
    }
    if (align) {
        style.textAlign = align;
      }
    return style;
  },
  onOrder: function (dataKey) {
    if (this.state.order == '' || this.state.order == 'desc') {
      //分页
      //this.setState({rowData: this.state.rowData.sort(function(a,b) {return a[dataKey] - b[dataKey]}), order: 'asce'});
      /*let data = this.Divide(this.state.rowData, this.state.pageSize);
      this.setState({
        data: data[this.state.currentPage-1],
        totalNumber: this.state.rowData.length,
      });*/
      let rowData = this.props.data;
      let orderData = rowData.sort(function(a,b) {return a[dataKey] - b[dataKey]});
      this.setState({data: orderData, order: 'asce'});
    } else if (this.state.order == 'asce') {
      //this.setState({rowData: this.state.rowData.sort(function(a,b) {return b[dataKey] - a[dataKey]}), order: 'desc'});
      /*let data = this.Divide(this.state.rowData, this.state.pageSize);
      this.setState({
        data: data[this.state.currentPage-1],
        totalNumber: this.state.rowData.length,
      });*/
      let rowData = this.props.data;
      let orderData = rowData.sort(function(a,b) {return b[dataKey] - a[dataKey]});
      this.setState({data: orderData, order: 'desc'});
    }
  },
  getThStyle: function({ width, align, order }) {
    const style = {};
    if (width) {
        style.width = width;
    }
    if (align) {
        style.textAlign = align;
    }
    /*if(/true/i.test(order)) {
      style.background = `url(${orderIcon}) no-repeat 6px 12px`;
      style.cursor = "pointer";
    }*/
    return style
  },
  getImgStyle: function() {
    const style = {};
    style.cursor = "pointer";
    style.position = "relative";
    style.top = "2px";
    style.left = "2px";
    return style;
  },

  renderThs: function(columns) {
    return (
      columns.map((col, index) => {     
        const { name, dataKey, th, order } = col.props;
        const props = { name, dataKey, colIndex: index};
        let content;
        let className;//处理th为节点的情况时，要将class样式也复制过来
        
        if (React.isValidElement(th)) { //判断th是否为ReactElement
          content = React.cloneElement(th, props);
          //className = this.getDisplayName(th);
        } else if (isFunction(th)) { 
          content = th(props);
        } else {
          content = name || '';
        }

        /*return (
          <th
            key={`th-${index}`}
            style={this.getThStyle(col.props)}
            onClick={/true/i.test(order)? this.onOrder.bind(this,dataKey) : ''}
            className={`table-th col-${index} col-${dataKey} ${className || ''}`}
          >
            {content}
          </th> 
        );*/
        if(/true/i.test(order)) {
          return (
            <th
              key={`th-${index}`}
              style={this.getThStyle(col.props)}
              onClick={/true/i.test(order)? this.onOrder.bind(this,dataKey) : ''}
              className={`table-th col-${index} col-${dataKey} ${className || ''}`}
            >
              {content}
              <img src={orderIcon} style={this.getImgStyle()} height="15px" width="15px" />
            </th> 
          );
        } else {
          return (
            <th
              key={`th-${index}`}
              style={this.getThStyle(col.props)}
              onClick={/true/i.test(order)? this.onOrder.bind(this,dataKey) : ''}
              className={`table-th col-${index} col-${dataKey} ${className || ''}`}
            >
              {content}
            </th> 
          );
        }
      })
    );
  },

  renderTds: function(data, entry, columns, rowIndex) {
    // 传入数据数组，数据数组的元素，列数组，行位置
    return (
      columns.map((col, index) => {
        const { dataKey, td } = col.props;
        const value = entry[dataKey];
        const props = { data, rowData: entry, tdValue: value, dataKey, rowIndex, colIndex: index};

        let content;
        let className;

        if (React.isValidElement(td)) {
          content = React.cloneElement(td, props);
          className = getDisplayName(td);
        } else if (isFunction(td)) {
          content = td(props);
          className = td.name;
        } else {
          content = value;
        }
        //生成行时调用，行数据对应的每一列都返回td
        return (
          <td
            key={`td-${index}`}
            style={this.getStyle(col.props)}
            className={`table-td col-${index} col-${dataKey} ${className || ''}`}
          >
            {content}
          </td> 
        );
      })
    );
  },

  renderRows: function(data, columns) {
    if (!data || !data.length) {return null;}
    //data将一整行的数据存放为数组的一个元素
    return (data.map((entry, index) => {
      return (
        <tr className={`tr-${index}`} key={`tr-${index}`}>
          {this.renderTds(data, entry, columns, index)}
        </tr> 
      );
    })
    );
  },
  renderTfoots: function(data, columns) {
    if(this.props.needSum == 'false') { return }

    /*const { name, dataKey, th, order } = col.props;
    let name = Object.keys(data[0]);
    let a = new Array(name.length);
    let needless = true;
    a.fill(0);
    //将数据合计处理并保存为数组形式
    columns.map((col, index) => {
      for(let i=0; i<data.length; i++) {
        let object = data[i];
        let prop = name[index];
        a[index] = a[index] + object[prop];
      }
      //纠正'合计'位置
      if(!(/number/.test(typeof a[index]))) {
        console.log(index+1, a[index]);
        a[index] = '合计';
        needless = false;       
        //console.log(i+1,index+1);
      } else {
        if(!Number.isInteger(parseFloat(a[index]))) {
          a[index] = a[index].toFixed(2);
        } else {
          parseInt(a[index]);
        }
      }
    });
    if(needless) {
      return;
    }

    let name = Object.keys(data[0]);

    let needless = true;*/

    return (
      columns.map((col, index) => {
        const { dataKey } = col.props; 
        let sum = 0;
        
        if(dataKey=='shopName'||dataKey=='servantName') {
          return (
            <td key={`col-${dataKey}`}>合计</td>
          );
        } else {
          for(let i=0; i<data.length; i++) {
            let dataObject = data[i];
            let value = dataObject[dataKey];
            sum += value;
          }
          if(/number/.test(typeof (sum))) {
            return (
              <td key={`col-${dataKey}`}>{sum}</td>
            ); 
          } else {
            return (
              <td key={`col-${dataKey}`}></td>
            );
          }
        }       
      })
    ); 
  },

  //分页功能的页码改变,子组件通过this.props.onChange调用
  /*handleChange: function(idx) {
    //console.log('页码改变 => ', idx);
    //放里面感觉影响性能，放外面怕全局污染...
    let rowData = this.props.data;
    let data = this.Divide(rowData, this.state.pageSize);
    this.setState({
      currentPage: idx,
      data: data[idx - 1]
    });
    //setState可能会为了性能批量设置state后再渲染(文档上说的)
  },*/

  render: function() {
    const { children, className } = this.props;
    const columns = findAllByType(children, Column);
    //console.log(this.props.data);
    let sumData = this.state.data
    console.log(sumData);
    if(!(columns&&sumData[0])) {return null} else{
      return (
      <div className={`react-smart-table-container ${className || ''}`}>
      <table className="react-smart-table">
        {this.hasNames(columns) && (
        <thead className="react-smart-table-thead">
          <tr className="react-smart-table-tr">
            {this.renderThs(columns)}
          </tr>
        </thead>
        )}
        <tbody className="react-smart-table-tbody">
          {this.renderRows(this.state.data, columns)}
        </tbody>
        <tfoot>
          <tr className="react-smart-table-tr">
            {this.renderTfoots(this.state.rowData, columns)}
          </tr>
        </tfoot>
      </table>
      {/*<Pagination 
        totalNumber={this.state.totalNumber}
        pageSize={this.state.pageSize}
        currentPage={this.state.currentPage}
        middlePage={5}
        onChange={this.handleChange}
        showPages={false}
        showPrev
        showNext
      />*/}
      </div>
    );
    }
    
    
  },

  componentWillReceiveProps: function(nextProps) {
      //var rowData = nextProps.data;
      //let data = this.Divide(rowData, this.state.pageSize);
      this.setState({
        data: nextProps.data,
        //data: data[this.state.currentPage-1],
        rowData: nextProps.data,
        //totalNumber: nextProps.data.length,
      });
  }


});